package com.bblocks.message.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import com.bblocks.pojo.ComUser;
import com.google.common.collect.Lists;
import com.bblocks.message.api.JMessageClient;
import com.bblocks.message.api.common.model.message.MessageDto;
import com.bblocks.message.api.message.MessageListResult;
import com.bblocks.message.api.message.MessageResult;
import com.bblocks.message.api.utils.GuardUtils;
import com.bblocks.message.service.ImMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:消息实现类
 * @author: xingdong
 * @time: 2020/6/17 下午8:54
 */
@Service
public class ImMessageServiceImpl implements ImMessageService {

    protected static final Logger log = LoggerFactory.getLogger(ImMessageServiceImpl.class);

    //@Autowired
    //private UserMapper userMapper;

    JMessageClient client = new JMessageClient(GuardUtils.appkey.getValue(), GuardUtils.masterSecret.getValue());

    @Override
    public List<MessageDto> getMessageList(ComUser cuser) {
        String phone =  cuser.getPhone();
        List<MessageDto> resultMessageList = new ArrayList<>();
        List<MessageResult> messageList = getMessageResultList(cuser.getPhone());
        //没有消息直接返回
        if(CollectionUtils.isEmpty(messageList)){
            return Lists.newArrayList();
        }
        //取出所有聊天用户并去重
        List<String> chatBodyList = messageList.stream().map(message -> {
            String chatBody = "";
            if (cuser.getPhone().equals(message.getTargetId())) {
                chatBody = message.getFromId();
            } else if (cuser.getPhone().equals(message.getFromId())) {
                chatBody = message.getTargetId();
            }
            return chatBody;
        }).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
        // 遍历去重后的用户聊天信息，获取与该用户的聊天记录
        resultMessageList = chatBodyList.stream().map(imName -> {
            MessageDto messageDto = new MessageDto();
            if (!NumberUtil.isNumber(imName)) {
				return messageDto;
			}
            /**
            User chatUser = userMapper.getUserByPhone(imName);
            if (chatUser == null) {
                throw new ServiceException(SysEnum.NO_USER);
            }
			 **/
            Integer appType = cuser.getAppType();
            messageDto.setOwnerUsername(cuser.getName());
            messageDto.setOwnerHeadPicture(cuser.getAvatar());
            //messageDto.setChatUsername(chatUser.getRealName());
            //messageDto.setChatHeadPicture(chatUser.getHeadPicture());
            List<MessageResult> messageResultList = messageList.stream()
                    .filter(resultMessage -> imName.equals(resultMessage.getTargetId()) || imName.equals(resultMessage.getFromId()))
                    .collect(Collectors.toList());
            messageDto.setMessageResultList(messageResultList);
            return messageDto;
        }).collect(Collectors.toList());

    return resultMessageList;

    }

    @Override
    public MessageDto getUserMessageDetails(ComUser targetUser, ComUser cuser) {
        /*User chatUser = userMapper.getUserByPhone(chatUsername);
        if (chatUser == null) {
            throw new ServiceException(SysEnum.NO_USER);
        }*/
        List<MessageResult> messageList = getMessageResultList(cuser.getPhone());
        MessageDto messageDto = new MessageDto();
        //没有消息直接返回
        if(CollectionUtils.isEmpty(messageList)){
            return null;
        }
        List<MessageResult> resultList = messageList.stream()
                .filter(message -> targetUser.getPhone().equals(message.getTargetId()) || targetUser.getPhone().equals(message.getFromId()))
                .collect(Collectors.toList());
        messageDto.setOwnerUsername(cuser.getName());
        messageDto.setOwnerHeadPicture(cuser.getAvatar());
        messageDto.setChatUsername(targetUser.getName());
        messageDto.setChatHeadPicture(targetUser.getAvatar());
        messageDto.setMessageResultList(resultList);
        return messageDto;
    }

    public List<MessageResult> getMessageResultList(String username) {
        List<MessageResult> messageResultList = new ArrayList<MessageResult>();
        try {
			DateTime now = DateUtil.date();
            String endDate = DateUtil.format(now, DatePattern.NORM_DATETIME_FORMAT);
            String beginDate = DateUtil.format(DateUtil.offsetDay(now,-7), DatePattern.NORM_DATETIME_FORMAT);
            MessageListResult result = client.getUserMessages(username, 1000, beginDate, endDate);
            MessageResult[] messages = result.getMessages();
//            String cursor = result.getCursor();
//            if (StringUtils.isNotEmpty(cursor)) {
//                client.getUserMessagesByCursor(username, cursor);
//            }
            messageResultList = Arrays.asList(messages);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Message: " + e.getMessage());
        }
        return messageResultList;
    }

}
